package com.qipa.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.ImmediateEventExecutor;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class ServerHandler extends SimpleChannelInboundHandler<String> {

    Logger logger = Logger.getLogger(ServerHandler.class);

    //使用DefaultChannelGroup保存所有WebSocket客户端
    private static final ChannelGroup channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //客户端连接会来这里
        Channel channel = ctx.channel();
        //该方法会将channelGroup中所有的channel遍历，并发送消息
        channel.writeAndFlush("[ 客户端 ]" + channel.remoteAddress() + "上线了，时间：" + sdf.format(new Date()));
        //将当前的channel加入到channelGroup
        channelGroup.add(channel);

        logger.info(channel.localAddress() + "客户端连上了...");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.forEach((ch) -> {
            if (channel == ch) {//不是当前的channel，转发消息
                ch.writeAndFlush("[ 客户端 ]" + channel.remoteAddress() + "发送了消息：" + msg + "\n");
            } else {
                //回显自己发送的消息给自己
                ch.writeAndFlush("[ 自己 ]发送了消息" + msg + "\n");
            }
        });
    }


}
